package com.pingan.internal.point.shopping.common.aspect;


import com.pingan.internal.point.common.enums.ResultCodeEnum;
import com.pingan.internal.point.common.exceptions.WrappedException;
import com.pingan.internal.point.common.model.ApiResultEntity;
import com.pingan.internal.point.shopping.common.exception.BusinessException;
import com.pingan.internal.point.shopping.common.msg.ErrorMessage;
import com.pingan.internal.point.shopping.controller.response.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionAdvice {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionAdvice.class);

    @ResponseBody
    @ExceptionHandler(value= BusinessException.class)
    public ResponseData errorHandler(BusinessException ex){
        LOGGER.error("GlobalExceptionAdvice_errorHandler_error_",ex);
        return ResponseData.error(ex.getCode(),ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value= WrappedException.class)
    public ResponseData errorHandler(WrappedException ex){
        LOGGER.error("GlobalExceptionAdvice_errorHandler_error_",ex);
        return ResponseData.error(ex.getCode(),ex.getMessage());
    }

    @ExceptionHandler(value = ObjectOptimisticLockingFailureException.class)
    public ApiResultEntity errorHandler(ObjectOptimisticLockingFailureException ex) {
        throw ex;
    }

    @ResponseBody
    @ExceptionHandler(value = AccessDeniedException.class)
    public ResponseData errorHandler(AccessDeniedException ex) {
        LOGGER.error(ResultCodeEnum.ACCESS_DENIED.getCode(), ex);
        return ResponseData.error(ResultCodeEnum.ACCESS_DENIED.getCode(), ex.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value= Exception.class)
    public ResponseData errorException(Exception ex){
        LOGGER.error("GlobalExceptionAdvice_errorHandler_error_",ex);
        return ResponseData.error(ErrorMessage.UNKNOWN);
    }
}
